package com.ztom.daily.n2022.m4;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 最常见的单词
 * <p>
 * https://leetcode-cn.com/problems/most-common-word/
 *
 * @author ZhangTao
 */
public class Day17MostCommonWord {

    public String mostCommonWord(String paragraph, String[] banned) {
        // 转 set 方便判断
        Set<String> ban = Arrays.stream(banned).collect(Collectors.toSet());
        int max = 0;
        // 记录单词出现次数
        Map<String, Integer> count = new HashMap<>();
        StringBuilder builder = new StringBuilder();
        int len = paragraph.length();
        for (int i = 0; i <= len; i++) {
            if (i < len && Character.isLetter(paragraph.charAt(i))) {
                // 拼接单词
                builder.append(Character.toLowerCase(paragraph.charAt(i)));
            } else if (builder.length() > 0) {
                // 记录单词次数
                String word = builder.toString();
                if (!ban.contains(word)) {
                    int n = count.getOrDefault(word, 0) + 1;
                    count.put(word, n);
                    max = Math.max(max, n);
                }
                builder.setLength(0);
            }
        }
        return count.entrySet().stream().max(Map.Entry.comparingByValue()).get().getKey();
    }
}
